<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;

class Sync extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'sync:boot';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Sync addresses of transaction';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        daemonize();

        while (true) {

            if (Storage::exists('ethereum/addresses.json')) {

                $addresses = json_decode(Storage::get('ethereum/addresses.json'), true);
                $files = Storage::allFiles('pids');
                $exists_addresses = [];

                foreach ($files as $file) {
                    $file_info = pathinfo(Storage::path($file));
                    list($address, $pid) = explode('-', $file_info['filename']);

                    $exists_addresses[$address] = $pid;
                }

                foreach ($addresses as $value) {
                    if (isset($exists_addresses[$value])) {
                        if (!posix_kill($exists_addresses[$value], 0)) {
                            $pid = pcntl_fork();

                            if ($pid == 0) {
                                $this->call('sync:transactions', [
                                    'address' => $value,
                                    '--loop' => 'default',
                                ]);
                            } elseif ($pid < 0) {
                                $this->error('fork failed');
                            } else {
                                $status = '';
                                pcntl_waitpid($pid, $status);
                            }
                            
                        }
                    } else {
                        $pid = pcntl_fork();

                        if ($pid == 0) {
                            $this->call('sync:transactions', [
                                'address' => $value,
                                '--loop' => 'default',
                            ]);
                        } elseif ($pid < 0) {
                            $this->error('fork failed');
                        } else {
                            $status = '';
                            pcntl_waitpid($pid, $status);
                        }
                    }
                    
                }
            }

            sleep(60);
        }
    }
}
